<template>
  <transition name="fade">
    <div class="input-wrapper" v-if="show">
      <el-input
          class="gray-bg-input"
          maxlength="100"
          show-word-limit
          v-model="inputComment"
          type="textarea"
          :rows="3"
          @focusin="inputFocus"
          @blur="blur"
          :placeholder="name"
      ></el-input>
      <transition name="fade2">
        <div class="btn-control" v-show="controlShow">
          <el-row>
            <el-col :span="12" style="text-align: right">
              <span class="cancel" @click="cancel">取消</span>
              <el-button class="btn" type="success" round @click="commitComment">确定</el-button>
            </el-col>
          </el-row>
        </div>
      </transition>
    </div>
  </transition>
</template>

<script setup>

import { defineProps, ref, watch, onMounted } from 'vue';

const { show, value, toComment, toId, type } = defineProps([
  'show',
  'value',
  'toComment',
  'toId',
  'type',
]);

const inputComment = ref('');
const name = ref('');
const id = ref('');
const controlShow = ref(false);
const cursorIndexStart = ref(null);
const cursorIndexEnd = ref(null);

watch([() => toComment, () => toId], ([toCommentVal, toIdVal], [oldToCommentVal, oldToIdVal]) => {
  name.value = toCommentVal;
  id.value = toIdVal;
  inputComment.value = '';
});


onMounted(()=>{
  if (type === 'END'){
    controlShow.value = false;
  }else {
    controlShow.value = true;
  }
});
function cancel() {
  if (type === 'end') {
    controlShow.value = false;
  }
  $emit('cancel');
}

function commitComment() {
  $emit('confirm', { inputComment: inputComment.value, id: id.value });
  inputComment.value = '';
}

function inputFocus() {
  if (type === 'end') {
    controlShow.value = true;
  }
}

function blur(e) {
  cursorIndexStart.value = e.target.selectionStart;
  cursorIndexEnd.value = e.target.selectionEnd;
}

function output(val) {
  if (cursorIndexStart.value !== null && inputComment.value) {
    inputComment.value = inputComment.value.substring(0, cursorIndexStart.value) + val + inputComment.value.substring(cursorIndexEnd.value);
  } else {
    inputComment.value = (inputComment.value ? inputComment.value : '') + val;
  }
}
</script>

<style scoped rel="stylesheet/scss" lang="scss">

.fade-enter-active, fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

.input-wrapper {
  padding: 10px;

  .fade2-enter-active, fade2-leave-active {
    transition: opacity 0.5s;
  }

  .fade2-enter, .fade2-leave-to {
    opacity: 0;
  }
  .gray-bg-input, .el-input__inner {
    /*background-color: #67C23A;*/
  }
  .btn-control {
    justify-content: flex-end;
    align-items: center;
    padding-top: 10px;
    .cancel {
      font-size: 16px;
      color: #606266;
      margin-right: 20px;
      cursor: pointer;
      &:hover {
        color: #333;
      }
    }
    .confirm {
      font-size: 16px;
    }
  }
}
</style>
